<template>
  <el-dialog v-model="visible" title="选择地址" width="800px" :before-close="handleClose" destroy-on-close>
    <div class="map-container">
      <!-- 搜索框 -->
      <div class="search-box" ref="searchBoxRef">
        <el-input v-model="searchKeyword" placeholder="请输入地址关键词搜索" @input="handleSearchInput" @focus="handleSearchFocus"
          @clear="handleSearchClear" clearable>
          <template #append>
            <el-button @click="searchAddress" :loading="searching">
              <i class="el-icon-search"></i>
            </el-button>
          </template>
        </el-input>
      </div>

      <!-- 搜索结果列表 -->
      <div v-if="searchResults.length > 0" class="search-results">
        <div class="results-title">搜索结果：</div>
        <div class="results-list">
          <div v-for="(item, index) in searchResults" :key="index" class="result-item"
            :class="{ active: selectedResult === item }" @click="selectSearchResult(item)">
            <div class="result-name">{{ item.name }}</div>
            <div class="result-address">{{ item.province }}{{ item.city }}{{ item.district }}{{ item.address }}</div>
          </div>
        </div>
      </div>

      <!-- 地图容器 -->
      <div id="amap-container" class="map-wrapper"></div>

      <!-- 选中的地址信息 -->
      <div v-if="selectedAddress" class="selected-info">
        <div class="info-title">已选择地址：</div>
        <div class="info-content">
          <div><strong>地址：</strong>{{ selectedAddress.address }}</div>
          <div><strong>经纬度：</strong>{{ selectedAddress.lng }}, {{ selectedAddress.lat }}</div>
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="confirmSelection" :disabled="!selectedAddress">
          确认选择
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, watch, nextTick, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import AMapLoader from "@amap/amap-jsapi-loader"

export default {
  name: 'MapAddressSelector',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    // 默认经纬度
    defaultLng: {
      type: [Number, String],
      default: null
    },
    defaultLat: {
      type: [Number, String],
      default: null
    },
    // 默认地址
    defaultAddress: {
      type: String,
      default: ''
    }
  },
  emits: ['update:modelValue', 'confirm'],
  setup(props, { emit }) {
    // 高德地图配置
    window._AMapSecurityConfig = {
      securityJsCode: "3df6beab1b8e671a74db77c89353880b"
    }

    const visible = ref(false)
    const searchKeyword = ref('')
    const searching = ref(false)
    const searchResults = ref([])
    const selectedResult = ref(null)
    const selectedAddress = ref(null)
    const searchBoxRef = ref(null)

    let map = null
    let marker = null
    let placeSearch = null
    let geocoder = null
    let AMap = null

    // 监听弹窗显示状态
    watch(() => props.modelValue, (newVal) => {
      visible.value = newVal
      if (newVal) {
        nextTick(() => {
          initMap()
        })
      }
    })

    // 搜索防抖定时器
    let searchTimer = null

    watch(visible, (newVal) => {
      emit('update:modelValue', newVal)
    })

    // 初始化地图
    const initMap = () => {
      AMapLoader.load({
        key: "385abde6dd3e2894bf3dd0043f4a2978",
        version: "2.0",
        plugins: ["AMap.PlaceSearch", "AMap.Geocoder"]
      })
        .then((AmapInstance) => {
          console.log('地图加载成功')
          AMap = AmapInstance
          createMap()
        })
        .catch((e) => {
          console.error('地图加载失败:', e)
          ElMessage.error('地图服务加载失败，请检查网络连接')
        })
    }

    // 创建地图
    const createMap = () => {
      try {
        console.log('开始创建地图')
        map = new AMap.Map('amap-container', {
          zoom: 13,
          center: [116.397428, 39.90923], // 默认北京
          mapStyle: 'amap://styles/normal'
        })

        // 初始化搜索服务
        placeSearch = new AMap.PlaceSearch({
          pageSize: 10,
          pageIndex: 1,
          city: '全国'
        })
        console.log('搜索服务初始化完成')

        // 初始化地理编码服务
        geocoder = new AMap.Geocoder({
          city: '全国'
        })
        console.log('地理编码服务初始化完成')

        // 地图点击事件
        map.on('click', (e) => {
          console.log('地图点击事件:', e.lnglat)
          const { lng, lat } = e.lnglat
          setMarker(lng, lat)
          reverseGeocode(lng, lat)
        })

        // 检查是否有默认位置
        if (props.defaultLng && props.defaultLat) {
          const lng = parseFloat(props.defaultLng)
          const lat = parseFloat(props.defaultLat)
          map.setCenter([lng, lat])
          setMarker(lng, lat)
          if (props.defaultAddress) {
            selectedAddress.value = {
              address: props.defaultAddress,
              lng: lng,
              lat: lat
            }
          } else {
            reverseGeocode(lng, lat)
          }
        } else {
          // 获取用户当前位置
          getCurrentLocation()
        }
      } catch (error) {
        console.error('创建地图失败:', error)
        ElMessage.error('地图初始化失败')
      }
    }

    // 获取当前位置
    const getCurrentLocation = () => {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            const { longitude, latitude } = position.coords
            map.setCenter([longitude, latitude])
            setMarker(longitude, latitude)
            reverseGeocode(longitude, latitude)
          },
          () => {
            console.log('无法获取当前位置，使用默认位置')
          }
        )
      }
    }

    // 处理搜索输入
    const handleSearchInput = () => {
      if (searchTimer) {
        clearTimeout(searchTimer)
      }

      searchTimer = setTimeout(() => {
        if (searchKeyword.value.trim()) {
          searchAddress()
        } else {
          searchResults.value = []
        }
      }, 500) // 500ms 防抖
    }

    // 处理搜索框获得焦点
    const handleSearchFocus = () => {
      // 如果有搜索关键词且有结果，重新显示搜索结果
      if (searchKeyword.value.trim() && searchResults.value.length === 0) {
        searchAddress()
      }
    }

    // 处理搜索框清空
    const handleSearchClear = () => {
      searchResults.value = []
      if (searchTimer) {
        clearTimeout(searchTimer)
      }
    }

    // 处理点击外部区域
    const handleClickOutside = (event) => {
      if (searchBoxRef.value && !searchBoxRef.value.contains(event.target)) {
        // 检查点击的是否是搜索结果区域
        const searchResultsEl = document.querySelector('.search-results')
        if (!searchResultsEl || !searchResultsEl.contains(event.target)) {
          searchResults.value = []
        }
      }
    }

    // 搜索地址
    const searchAddress = () => {
      if (!searchKeyword.value.trim()) {
        searchResults.value = []
        return
      }

      if (!placeSearch) {
        ElMessage.error('地图服务未初始化，请稍后再试')
        return
      }

      searching.value = true
      console.log('开始搜索:', searchKeyword.value)

      placeSearch.search(searchKeyword.value, (status, result) => {
        searching.value = false
        console.log('搜索结果:', status, result)

        if (status === 'complete' && result.poiList && result.poiList.pois) {
          searchResults.value = result.poiList.pois.map(poi => ({
            name: poi.name,
            address: poi.address || '',
            district: poi.district || '',
            province: poi.pname || '',
            city: poi.cityname || '',
            lng: poi.location.lng,
            lat: poi.location.lat
          }))
          console.log('处理后的搜索结果:', searchResults.value)
        } else {
          searchResults.value = []
          if (searchKeyword.value.trim()) {
            ElMessage.warning('未找到相关地址')
          }
        }
      })
    }

    // 选择搜索结果
    const selectSearchResult = (item) => {
      console.log('选择搜索结果:', item)
      selectedResult.value = item
      if (map) {
        map.setCenter([item.lng, item.lat])
        map.setZoom(16) // 放大地图
      }
      setMarker(item.lng, item.lat)

      // 构建完整地址，包含省份和城市
      let fullAddress = ''
      if (item.province) fullAddress += item.province
      if (item.city && item.city !== item.province) fullAddress += item.city
      if (item.district) fullAddress += item.district
      if (item.address) fullAddress += item.address
      if (item.name) fullAddress += item.name

      selectedAddress.value = {
        address: fullAddress || `${item.name}`,
        province: item.province || '',
        city: item.city || '',
        district: item.district || '',
        lng: item.lng,
        lat: item.lat
      }
      searchResults.value = []
      console.log('设置选中地址:', selectedAddress.value)
    }

    // 设置标记点
    const setMarker = (lng, lat) => {
      if (marker) {
        marker.setPosition([lng, lat])
      } else {
        marker = new AMap.Marker({
          position: [lng, lat],
          draggable: true
        })
        map.add(marker)

        // 标记点拖拽事件
        marker.on('dragend', (e) => {
          const { lng, lat } = e.lnglat
          reverseGeocode(lng, lat)
        })
      }
    }

    // 逆地理编码
    const reverseGeocode = (lng, lat) => {
      if (!geocoder) {
        console.error('地理编码服务未初始化')
        return
      }

      console.log('开始逆地理编码:', lng, lat)
      geocoder.getAddress([lng, lat], (status, result) => {
        console.log('逆地理编码结果:', status, result)
        if (status === 'complete' && result.regeocode) {
          const regeocode = result.regeocode
          const addressComponent = regeocode.addressComponent

          selectedAddress.value = {
            address: regeocode.formattedAddress,
            province: addressComponent.province || '',
            city: addressComponent.city || '',
            district: addressComponent.district || '',
            lng: lng,
            lat: lat
          }
          console.log('设置选中地址:', selectedAddress.value)
        } else {
          console.error('逆地理编码失败:', status, result)
          // 即使逆地理编码失败，也保存坐标信息
          selectedAddress.value = {
            address: `位置: ${lng.toFixed(6)}, ${lat.toFixed(6)}`,
            province: '',
            city: '',
            district: '',
            lng: lng,
            lat: lat
          }
        }
      })
    }

    // 确认选择
    const confirmSelection = () => {
      if (selectedAddress.value) {
        emit('confirm', selectedAddress.value)
        handleClose()
      }
    }

    // 关闭弹窗
    const handleClose = () => {
      visible.value = false
      searchKeyword.value = ''
      searchResults.value = []
      selectedResult.value = null
      selectedAddress.value = null
      if (searchTimer) {
        clearTimeout(searchTimer)
        searchTimer = null
      }
      if (marker && map) {
        map.remove(marker)
        marker = null
      }
    }

    // 监听弹窗打开时添加点击外部事件
    watch(visible, (newVal) => {
      if (newVal) {
        nextTick(() => {
          document.addEventListener('click', handleClickOutside)
        })
      } else {
        document.removeEventListener('click', handleClickOutside)
      }
    })

    // 组件卸载时清理事件监听
    onUnmounted(() => {
      document.removeEventListener('click', handleClickOutside)
      if (searchTimer) {
        clearTimeout(searchTimer)
      }
    })

    return {
      visible,
      searchKeyword,
      searching,
      searchResults,
      selectedResult,
      selectedAddress,
      searchBoxRef,
      handleSearchInput,
      handleSearchFocus,
      handleSearchClear,
      searchAddress,
      selectSearchResult,
      confirmSelection,
      handleClose
    }
  }
}
</script>

<style scoped>
.map-container {
  height: 500px;
  display: flex;
  flex-direction: column;
  position: relative;
}

.search-box {
  margin-bottom: 10px;
  position: relative;
  z-index: 10;
}

.search-results {
  position: absolute;
  top: 50px;
  left: 0;
  right: 0;
  max-height: 200px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  z-index: 9999;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.results-list {
  max-height: 170px;
  overflow-y: auto;
}

.results-title {
  padding: 8px 12px;
  background-color: #f5f7fa;
  font-size: 12px;
  color: #909399;
  border-bottom: 1px solid #ebeef5;
}

.result-item {
  padding: 10px 12px;
  cursor: pointer;
  border-bottom: 1px solid #ebeef5;
  transition: background-color 0.2s;
}

.result-item:hover,
.result-item.active {
  background-color: #ecf5ff;
}

.result-item:last-child {
  border-bottom: none;
}

.result-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.result-address {
  font-size: 12px;
  color: #909399;
}

.map-wrapper {
  flex: 1;
  min-height: 300px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.selected-info {
  margin-top: 10px;
  padding: 10px;
  background-color: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 4px;
}

.info-title {
  font-weight: 500;
  color: #409eff;
  margin-bottom: 8px;
}

.info-content div {
  margin-bottom: 4px;
  font-size: 14px;
  color: #606266;
}

.info-content div:last-child {
  margin-bottom: 0;
}
</style>